<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋对战平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#722ED1',
                        neutral: '#F5F7FA',
                        'neutral-dark': '#1D2129',
                        'board-bg': '#E6A86D',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 30px rgba(0, 0, 0, 0.08)',
                        'elevated': '0 15px 35px rgba(0, 0, 0, 0.12)',
                    }
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .message-appear {
                animation: messageAppear 0.3s ease-out forwards;
            }
            .message-disappear {
                animation: messageDisappear 0.3s ease-in forwards;
            }
            @keyframes messageAppear {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            @keyframes messageDisappear {
                from { opacity: 1; transform: translateY(0); }
                to { opacity: 0; transform: translateY(-10px); }
            }
            /* 关键优化：固定棋盘容器尺寸，避免重绘抖动 */
            .board-container {
                width: 100%;
                max-width: 400px;
                margin: 0 auto;
                aspect-ratio: 1 / 1;
                position: relative;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-neutral to-gray-100 min-h-screen font-inter text-neutral-dark">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-md backdrop-blur-sm bg-opacity-90 fixed w-full top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-gamepad text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">五子棋对战平台</h1>
            </div>
            <div id="room-info" class="hidden md:flex items-center space-x-2 text-sm">
                <span class="bg-primary/10 px-2 py-1 rounded-full text-primary">
                    房间号: <span id="room-id">--</span>
                </span>
                <span id="player-status" class="bg-green-100 px-2 py-1 rounded-full text-green-700">
                    <i class="fa fa-circle text-xs"></i> 连接中
                </span>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 pt-20 pb-16 flex flex-col md:flex-row gap-6">
        <!-- 游戏区域 -->
        <div class="w-full md:w-2/3 lg:w-3/4">
            <div class="bg-white rounded-xl shadow-card p-4 md:p-6 transform hover:shadow-elevated transition-all duration-300">
                <div class="mb-4 flex justify-between items-center">
                    <h2 class="text-lg font-semibold">游戏棋盘</h2>
                    <div id="game-status" class="bg-primary/10 text-primary px-3 py-1 rounded-full text-sm font-medium">
                        等待玩家连接...
                    </div>
                </div>
                
                <!-- 关键改进：使用绝对定位的消息容器，完全脱离文档流 -->
                <div id="message-container" class="relative h-6 mb-2">
                    <!-- 消息会动态添加到这里，使用绝对定位 -->
                </div>
                
                <!-- 棋盘容器 - 关键改进：使用固定比例容器避免尺寸抖动 -->
                <div class="board-container bg-board-bg rounded-lg overflow-hidden shadow-inner">
                    <canvas id="chess" class="w-full h-full"></canvas>
                    
                    <!-- 游戏状态覆盖层 -->
                    <div id="game-overlay" class="absolute inset-0 bg-black/50 flex items-center justify-center hidden">
                        <div class="bg-white p-6 rounded-xl text-center shadow-lg transform transition-all duration-500 scale-95 opacity-0" id="game-result">
                            <h3 class="text-2xl font-bold mb-4" id="result-text">游戏结束</h3>
                            <button id="restart-btn" class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105">
                                返回大厅
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 玩家信息 -->
                <div class="mt-6 grid grid-cols-2 gap-4">
                    <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <div class="w-10 h-10 rounded-full bg-white border-2 border-gray-300 flex items-center justify-center shadow-sm">
                            <div class="w-6 h-6 rounded-full bg-black"></div>
                        </div>
                        <div>
                            <div class="text-sm text-gray-500">黑方玩家</div>
                            <div id="black-player" class="font-medium">等待中...</div>
                        </div>
                        <div id="black-turn-indicator" class="ml-auto hidden">
                            <span class="bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded text-xs">
                                回合中
                            </span>
                        </div>
                    </div>
                    
                    <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                        <div class="w-10 h-10 rounded-full bg-white border-2 border-gray-300 flex items-center justify-center shadow-sm">
                            <div class="w-6 h-6 rounded-full bg-white border border-gray-300"></div>
                        </div>
                        <div>
                            <div class="text-sm text-gray-500">白方玩家</div>
                            <div id="white-player" class="font-medium">等待中...</div>
                        </div>
                        <div id="white-turn-indicator" class="ml-auto hidden">
                            <span class="bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded text-xs">
                                回合中
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 聊天区域 -->
        <div class="w-full md:w-1/3 lg:w-1/4">
            <div class="bg-white rounded-xl shadow-card p-4 md:p-6 h-[calc(100vh-12rem)] flex flex-col transform hover:shadow-elevated transition-all duration-300">
                <h2 class="text-lg font-semibold mb-4">聊天区域</h2>
                
                <!-- 聊天消息显示区 -->
                <div id="chat-show" class="flex-1 overflow-y-auto pr-2 mb-4 space-y-4">
                    <div class="flex items-start space-x-2 animate-fade-in">
                        <div class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center text-primary flex-shrink-0">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div>
                            <div class="bg-gray-100 rounded-lg rounded-tl-none px-3 py-2 max-w-[80%]">
                                欢迎来到五子棋对战平台，请等待其他玩家加入...
                            </div>
                            <span class="text-xs text-gray-400 mt-1 block">系统消息</span>
                        </div>
                    </div>
                </div>
                
                <!-- 聊天输入区 -->
                <div class="border-t pt-4">
                    <div class="flex gap-2">
                        <input type="text" id="chat-input" 
                            class="flex-1 border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
                            placeholder="输入消息...">
                        <button id="chat-button" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all transform hover:scale-105">
                            <i class="fa fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 移动端房间信息 -->
    <div class="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-3 flex justify-between items-center shadow-lg z-40">
        <span class="text-sm">房间号: <span id="mobile-room-id">--</span></span>
        <span class="text-xs bg-green-100 px-2 py-1 rounded-full text-green-700">
            <i class="fa fa-circle text-xs"></i> 在线
        </span>
    </div>

    <script>
        // 游戏常量和变量
        let chessBoard = [];
        const BOARD_ROW_AND_COL = 15;
        const chess = document.getElementById('chess');
        let context = chess.getContext('2d');
        let room_info = null;  // 存储房间信息，所有ID保持数字类型
        let is_me = false;
        let gameActive = true;
        let activeMessage = null; // 跟踪当前显示的消息

        // DOM元素
        const gameStatus = document.getElementById('game-status');
        const chatShow = document.getElementById('chat-show');
        const chatInput = document.getElementById('chat-input');
        const chatButton = document.getElementById('chat-button');
        const roomIdEl = document.getElementById('room-id');
        const mobileRoomIdEl = document.getElementById('mobile-room-id');
        const gameOverlay = document.getElementById('game-overlay');
        const gameResult = document.getElementById('game-result');
        const resultText = document.getElementById('result-text');
        const restartBtn = document.getElementById('restart-btn');
        const blackPlayerEl = document.getElementById('black-player');
        const whitePlayerEl = document.getElementById('white-player');
        const blackTurnIndicator = document.getElementById('black-turn-indicator');
        const whiteTurnIndicator = document.getElementById('white-turn-indicator');
        const messageContainer = document.getElementById('message-container');

        // WebSocket连接
        const ws_url = "ws://" + location.host + "/room";
        const ws_hdl = new WebSocket(ws_url);

        // 初始化棋盘尺寸 - 优化重绘逻辑
        function resizeCanvas() {
            // 强化防抖处理，避免频繁调整
            clearTimeout(window.resizeTimeout);
            window.resizeTimeout = setTimeout(() => {
                const container = chess.parentElement;
                if (!container) return;
                
                // 获取容器实际尺寸（考虑边框和内边距）
                const computedStyle = getComputedStyle(container);
                const paddingX = parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight);
                const paddingY = parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom);
                
                // 计算可用尺寸
                const containerWidth = container.clientWidth - paddingX;
                const containerHeight = container.clientHeight - paddingY;
                const size = Math.min(containerWidth, containerHeight);
                
                // 仅在尺寸变化超过1px时才重绘，避免微小波动导致的抖动
                if (Math.abs(chess.width - size) > 1) {
                    chess.width = size;
                    chess.height = size;
                    
                    // 同步Canvas显示尺寸
                    chess.style.width = `${size}px`;
                    chess.style.height = `${size}px`;
                    
                    console.log(`Canvas尺寸已更新: ${size}x${size}`);
                    
                    // 重新绘制棋盘和棋子
                    if (room_info) {
                        drawChessBoard();
                        redrawAllPieces();
                    }
                }
            }, 150); // 延长防抖时间，减少触发频率
        }

        // 初始化棋盘数据
        function initBoard() {
            chessBoard = [];
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = new Array(BOARD_ROW_AND_COL).fill(0);
            }
        }

        // 绘制棋盘
        function drawChessBoard() {
            const size = chess.width;
            const cellSize = size / BOARD_ROW_AND_COL;
            
            // 清除画布
            context.clearRect(0, 0, size, size);
            
            // 保存当前绘图状态
            context.save();
            
            // 绘制网格线
            context.strokeStyle = "#555";
            context.lineWidth = 1;
            
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                // 横线
                context.beginPath();
                context.moveTo(cellSize / 2, cellSize / 2 + i * cellSize);
                context.lineTo(size - cellSize / 2, cellSize / 2 + i * cellSize);
                context.stroke();
                
                // 竖线
                context.beginPath();
                context.moveTo(cellSize / 2 + i * cellSize, cellSize / 2);
                context.lineTo(cellSize / 2 + i * cellSize, size - cellSize / 2);
                context.stroke();
            }
            
            // 绘制天元和星位
            const starPoints = [
                {x: 3, y: 3}, {x: 11, y: 3},
                {x: 7, y: 7}, // 天元
                {x: 3, y: 11}, {x: 11, y: 11}
            ];
            
            starPoints.forEach(point => {
                drawStar(point.x, point.y, cellSize);
            });
            
            // 恢复绘图状态
            context.restore();
        }

        // 绘制星位
        function drawStar(x, y, cellSize) {
            const radius = cellSize / 10;
            
            // 保存当前绘图状态
            context.save();
            
            context.beginPath();
            context.arc(
                cellSize / 2 + x * cellSize,
                cellSize / 2 + y * cellSize,
                radius,
                0,
                2 * Math.PI
            );
            context.fillStyle = "#000";
            context.fill();
            
            // 恢复绘图状态
            context.restore();
        }

        // 重绘所有棋子
        function redrawAllPieces() {
            if (!room_info) return;
            
            // 保存当前绘图状态
            context.save();
            
            for (let row = 0; row < BOARD_ROW_AND_COL; row++) {
                for (let col = 0; col < BOARD_ROW_AND_COL; col++) {
                    const piece = chessBoard[row][col];
                    if (piece === 1) {
                        // 黑棋
                        oneStep(col, row, false);
                    } else if (piece === 2) {
                        // 白棋
                        oneStep(col, row, true);
                    }
                }
            }
            
            // 恢复绘图状态
            context.restore();
        }

        // 绘制棋子
        function oneStep(col, row, isWhite) {
            // 保存当前绘图状态，避免污染
            context.save();
            
            const cellSize = chess.width / BOARD_ROW_AND_COL;
            const x = cellSize / 2 + col * cellSize;
            const y = cellSize / 2 + row * cellSize;
            const radius = cellSize / 2 - 3;
            
            // 检查参数有效性
            if (isNaN(x) || isNaN(y) || radius <= 0) {
                console.error(`无效的棋子参数: col=${col}, row=${row}, x=${x}, y=${y}, radius=${radius}`);
                context.restore();
                return;
            }
            
            // 确保在画布范围内
            if (x - radius < 0 || x + radius > chess.width || 
                y - radius < 0 || y + radius > chess.height) {
                console.error(`棋子超出画布范围: x=${x}, y=${y}`);
                context.restore();
                return;
            }
            
            context.beginPath();
            context.arc(x, y, radius, 0, 2 * Math.PI);
            context.closePath();
            
            // 创建径向渐变，使棋子更有立体感
            const gradient = context.createRadialGradient(
                x - radius / 4, y - radius / 4, radius / 5,
                x + radius / 4, y + radius / 4, radius
            );
            
            if (!isWhite) {
                gradient.addColorStop(0, "#777");
                gradient.addColorStop(1, "#000");
            } else {
                gradient.addColorStop(0, "#FFF");
                gradient.addColorStop(1, "#CCC");
            }
            
            context.fillStyle = gradient;
            context.fill();
            
            // 棋子边缘
            context.strokeStyle = isWhite ? "#AAA" : "#222";
            context.lineWidth = 1;
            context.stroke();
            
            // 添加高光效果
            context.beginPath();
            context.arc(x, y, radius, 0, 2 * Math.PI);
            context.clip();
            
            const glow = context.createRadialGradient(
                x - radius / 2, y - radius / 2, 0,
                x, y, radius
            );
            glow.addColorStop(0, isWhite ? "rgba(255,255,255,0.6)" : "rgba(255,255,255,0.1)");
            glow.addColorStop(1, "rgba(255,255,255,0)");
            
            context.fillStyle = glow;
            context.fillRect(x - radius, y - radius, radius * 2, radius * 2);
            
            // 恢复绘图状态
            context.restore();
        }

        // 初始化游戏
        function initGame() {
            initBoard();
            drawChessBoard();
            setStatusIndicator(is_me);
        }

        // 设置游戏状态指示器
        function setStatusIndicator(meTurn) {
            if (!room_info) return;
            
            if (meTurn) {
                gameStatus.textContent = "轮到你走棋";
                gameStatus.className = "bg-green-100 text-green-700 px-3 py-1 rounded-full text-sm font-medium";
                showMessage("轮到你落子了", "info");
            } else {
                gameStatus.textContent = "等待对方走棋";
                gameStatus.className = "bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full text-sm font-medium";
                showMessage("等待对方落子...", "info");
            }
            
            // 更新玩家回合指示器
            const isWhiteTurn = meTurn === (room_info.uid === room_info.white_id);
            blackTurnIndicator.classList.toggle('hidden', isWhiteTurn);
            whiteTurnIndicator.classList.toggle('hidden', !isWhiteTurn);
        }

        // 显示游戏消息 - 关键改进：使用绝对定位完全脱离文档流
        function showMessage(text, type = "info") {
            // 如果已有活跃消息，先移除
            if (activeMessage) {
                activeMessage.classList.remove('message-appear');
                activeMessage.classList.add('message-disappear');
                // 动画结束后再移除元素，避免布局闪烁
                setTimeout(() => {
                    if (activeMessage && activeMessage.parentElement === messageContainer) {
                        messageContainer.removeChild(activeMessage);
                        activeMessage = null;
                    }
                }, 300);
            }
            
            // 创建新消息元素
            const messageEl = document.createElement('div');
            // 关键改进：使用绝对定位，固定位置，不影响布局
            messageEl.className = `absolute left-0 right-0 text-center py-1 px-3 rounded text-sm message-appear z-10 ${
                type === 'error' ? 'bg-red-100 text-red-700' :
                type === 'success' ? 'bg-green-100 text-green-700' :
                type === 'warning' ? 'bg-yellow-100 text-yellow-700' :
                'bg-blue-100 text-blue-700'
            }`;
            messageEl.textContent = text;
            
            // 添加到专用容器
            messageContainer.appendChild(messageEl);
            activeMessage = messageEl;
            
            // 3秒后自动移除
            setTimeout(() => {
                if (activeMessage === messageEl) {
                    messageEl.classList.remove('message-appear');
                    messageEl.classList.add('message-disappear');
                    setTimeout(() => {
                        if (messageEl.parentElement === messageContainer) {
                            messageContainer.removeChild(messageEl);
                            activeMessage = null;
                        }
                    }, 300);
                }
            }, 3000);
        }

        // 棋盘点击事件
        chess.onclick = function(e) {
            if (!gameActive || !is_me || !room_info) return;
            
            const rect = chess.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const cellSize = chess.width / BOARD_ROW_AND_COL;
            const col = Math.round((x - cellSize / 2) / cellSize);
            const row = Math.round((y - cellSize / 2) / cellSize);
            
            // 检查是否在有效范围内
            if (col < 0 || col >= BOARD_ROW_AND_COL || row < 0 || row >= BOARD_ROW_AND_COL) {
                showMessage("请在棋盘范围内落子", "warning");
                return;
            }
            
            // 检查位置是否已有棋子
            if (chessBoard[row][col] !== 0) {
                showMessage("当前位置已有棋子，请选择其他位置", "warning");
                return;
            }
            
            // 发送走棋请求
            sendChessMove(row, col);
        }

        // 发送走棋请求 - 确保所有数据为数字类型
        function sendChessMove(row, col) {
            if (!room_info) return;
            
            // 确保所有发送的ID和坐标都是数字类型
            const chessInfo = {
                optype: "put_chess",
                room_id: Number(room_info.room_id),
                uid: Number(room_info.uid),
                row: Number(row),
                col: Number(col)
            };
            
            ws_hdl.send(JSON.stringify(chessInfo));
        }

        // 发送聊天消息
        function sendChatMessage() {
            const message = chatInput.value.trim();
            if (!message || !room_info) return;
            
            const chatInfo = {
                optype: "chat",
                room_id: Number(room_info.room_id),
                uid: Number(room_info.uid),
                message: message
            };
            
            ws_hdl.send(JSON.stringify(chatInfo));
            chatInput.value = "";
        }

        // 添加聊天消息到界面
        function addChatMessage(message, isSelf = false, sender = "对方") {
            const messageEl = document.createElement('div');
            messageEl.className = `flex items-start space-x-2 animate-[fadeIn_0.3s_ease-in-out]`;
            
            const avatarClass = isSelf ? 
                "bg-primary text-white" : "bg-gray-200 text-gray-700";
            const messageBgClass = isSelf ? 
                "bg-primary text-white rounded-lg rounded-tr-none" : 
                "bg-gray-100 rounded-lg rounded-tl-none";
            
            messageEl.innerHTML = `
                <div class="w-8 h-8 rounded-full ${avatarClass} flex items-center justify-center flex-shrink-0">
                    <i class="fa fa-user"></i>
                </div>
                <div>
                    <div class="${messageBgClass} px-3 py-2 max-w-[80%]">
                        ${message}
                    </div>
                    <span class="text-xs text-gray-400 mt-1 block">${isSelf ? "我" : sender}</span>
                </div>
            `;
            
            chatShow.appendChild(messageEl);
            chatShow.scrollTop = chatShow.scrollHeight;
        }

        // 显示通知
        function showNotification(message, type = "info") {
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `fixed top-20 right-4 px-4 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-500 translate-x-full`;
            
            // 设置通知样式
            if (type === "error") {
                notification.classList.add("bg-red-500", "text-white");
            } else if (type === "success") {
                notification.classList.add("bg-green-500", "text-white");
            } else {
                notification.classList.add("bg-primary", "text-white");
            }
            
            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="fa fa-${type === 'error' ? 'exclamation-circle' : type === 'success' ? 'check-circle' : 'info-circle'} mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            // 显示通知
            setTimeout(() => {
                notification.classList.remove("translate-x-full");
                notification.classList.add("translate-x-0");
            }, 10);
            
            // 3秒后隐藏通知
            setTimeout(() => {
                notification.classList.remove("translate-x-0");
                notification.classList.add("translate-x-full");
                
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 500);
            }, 3000);
        }

        // 显示游戏结果
        function showGameResult(winnerId) {
            gameActive = false;
            
            if (winnerId === room_info.uid) {
                resultText.textContent = "恭喜，你赢了！";
                resultText.className = "text-2xl font-bold mb-4 text-green-600";
                showNotification("恭喜你获胜！", "success");
            } else if (winnerId === -1) {
                resultText.textContent = "游戏平局！";
                resultText.className = "text-2xl font-bold mb-4 text-yellow-600";
                showNotification("游戏平局！", "info");
            } else {
                resultText.textContent = "很遗憾，你输了！";
                resultText.className = "text-2xl font-bold mb-4 text-red-600";
                showNotification("很遗憾，你输了！", "info");
            }
            
            // 显示结果面板
            gameOverlay.classList.remove("hidden");
            setTimeout(() => {
                gameResult.classList.remove("scale-95", "opacity-0");
                gameResult.classList.add("scale-100", "opacity-100");
            }, 100);
        }

        // 事件监听
        chatButton.addEventListener('click', sendChatMessage);
        chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendChatMessage();
        });
        
        restartBtn.addEventListener('click', () => {
            // 关闭WebSocket连接
            ws_hdl.close();
            // 跳转到游戏大厅
            location.replace("/game_hall.html");
        });

        // 窗口大小变化时重新调整画布 - 减少触发频率
        window.addEventListener('resize', resizeCanvas);

        // 页面关闭时关闭WebSocket连接
        window.onbeforeunload = function() {
            ws_hdl.close();
        }

        // WebSocket事件处理
        ws_hdl.onmessage = function(evt) {
            try {
                const info = JSON.parse(evt.data);
                console.log("收到消息:", info);
                
                // 房间准备就绪
                if (info.optype === "room_ready") {
                    // 强制所有ID转换为数字类型
                    room_info = {
                        ...info,
                        room_id: Number(info.room_id),
                        uid: Number(info.uid),
                        white_id: Number(info.white_id),
                        black_id: Number(info.black_id)
                    };
                    
                    // 更新房间号显示
                    roomIdEl.textContent = room_info.room_id;
                    mobileRoomIdEl.textContent = room_info.room_id;
                    
                    // 更新玩家信息
                    blackPlayerEl.textContent = room_info.black_id === room_info.uid ? "你 (黑棋)" : "对手 (黑棋)";
                    whitePlayerEl.textContent = room_info.white_id === room_info.uid ? "你 (白棋)" : "对手 (白棋)";
                    
                    // 黑棋先行
                    is_me = room_info.uid === room_info.black_id;
                    initGame();
                    showNotification("房间已准备就绪，游戏开始！");
                } 
                // 走棋操作
                else if (info.optype === "put_chess") {
                    if (!info.result) {
                        showNotification(info.reason || "走棋失败", "error");
                        return;
                    }
                    
                    // 转换为数字类型
                    const row = Number(info.row);
                    const col = Number(info.col);
                    const uid = Number(info.uid);
                    
                    // 更新棋盘状态
                    if (row !== -1 && col !== -1 && 
                        row >= 0 && row < BOARD_ROW_AND_COL &&
                        col >= 0 && col < BOARD_ROW_AND_COL) {
                        
                        // 基于数字ID判断棋子颜色
                        const isWhite = uid === room_info.white_id;
                        chessBoard[row][col] = isWhite ? 2 : 1;
                        
                        // 绘制棋子
                        oneStep(col, row, isWhite);
                    }
                    
                    // 更新回合状态
                    is_me = uid !== room_info.uid;
                    setStatusIndicator(is_me);
                    
                    // 检查是否有胜利者
                    const winner = Number(info.winner);
                    if (winner !== 0) {
                        showGameResult(winner);
                    }
                } 
                // 聊天消息
                else if (info.optype === "chat") {
                    if (!info.result) {
                        showNotification(info.reason || "发送消息失败", "error");
                        return;
                    }
                    
                    // 转换为数字类型再比较
                    const senderUid = Number(info.uid);
                    const myUid = Number(room_info.uid);
                    const isSelf = senderUid === myUid;
                    const sender = isSelf ? "我" : "对手";
                    
                    addChatMessage(info.message, isSelf, sender);
                }
            } catch (e) {
                console.error("解析消息出错:", e);
                showNotification("接收消息出错", "error");
            }
        }

        // DOM加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            resizeCanvas();
        });
    </script>
</body>
</html>
